<template>
  <a-modal :width="boxShow?'1500px':'800px'" :dialogStyle="{ top: !boxShow?'20vh':'3vh'}" :visible="visible" cancelText="关闭" @cancel="visiblehandleCancel"> 
    <a-row v-if="editShow != 'edit'">
      <a-col :span="9">
        <a-row>
          <a-col :span="boxShow?2:4" style="line-height: 30px"> 姓名： </a-col>
          <a-col :span="20">
            <a-input-search
              v-model="searchValue"
              placeholder="请输入姓名"
              allowClear
              style="width: 300px"
              :class="noCardShow && 'no-user-input-style'"
              enter-button
              @search="onSearch"
              :loading="searchLoading"
              @click="inputClick"
            />
          </a-col>
        </a-row>
      </a-col>
    </a-row>
    <a-row v-if="boxShow" class="add-btn-style-pos-box">
      <div class="add-btn-style-pos">
        <a-row>
          <a-col :span="2">
            <a-button type="primary" @click="defaultShift('1', '早班')">
              默认早班
            </a-button>
          </a-col>
          <a-col :span="2">
            <a-button type="primary" @click="defaultShift('2', '中班')">
              默认中班
            </a-button>
          </a-col>
          <a-col :span="2">
            <a-button type="primary" @click="defaultShift('3', '夜班')">
              默认夜班
            </a-button>
          </a-col>
        </a-row>
      </div>

      <Calendar @select="onSelect" :defaultValue="moment().startOf('month').subtract(-1, 'month')" :validRange="[moment().startOf('month').subtract(-1, 'month'), moment().endOf('month').subtract(-1, 'month')]">
        <ul slot="dateCellRender" slot-scope="value" class="events" @click="ulClick($event)">
         
          <li class="calendar-li-style" v-for="item in getListData(value)" :key="item.content"> 
            <a-popover placement="rightTop" title="" trigger="click">
              <template slot="content">
                <p @click="addClick(elem.value)" v-for="elem in btnItemList" :key="elem.value" class="popover-style">{{elem.name}}</p> 
              </template>
              <!-- <a-tag :color="item.itemId == '4' ? '#f5680f':'#108ee9'" :style="'margin-bottom:10px'">
                {{item.content}} 
              </a-tag> -->
              <a-badge class="simulatedClick" :status="item.type" :text="item.content" />
              
              <a-icon class="calendar-li-icon-style" type="close" @click="removeTagsClick($event,item)" />
            </a-popover> 
          </li>
        </ul>
      
      </Calendar> 

    </a-row>

 

    <div v-if="noCardShow" :class="noCardShow && 'no-user-style'">暂无该用户，请重新输入</div>

    <template slot="footer">
      <a-button @click="visiblehandleCancel()">关闭</a-button>
      <a-button type="primary" @click="submit()" :disabled="!boxShow" :loading="submitLoading">确认</a-button>
    </template>
  </a-modal>
</template>
<script>
import {
  SchedulingSelectUser,
  SchedulingAddTbShift,
  SchedulingModifyQueryTbShift,
  SchedulingUpdateTbShift
} from '@/api/modular/main/rosterList/rosterList'
import moment from 'moment'
import { Calendar } from 'ant-design-vue';
export default {
  props: {
    row_record: {
      type: Object,
      default: () => {
        {
        }
      },
    },
  },
  components:{
    Calendar
  },
  data() {
    return {
      // 手术预约
      visible: false,
      boxShow: false,
      noCardShow: false,
      searchLoading: false,
      searchValue: '', 
      // 下拉数据
      selectDeptDataAll:[],

      searchUserinfo: {},  

      // 日历数据
      calendarList: [],
      clickDate:'',
      userDetailData: {},
      editShow: '',
      submitLoading: false,

      btnItemList: [
        {
          name:'早班',
          value: 1
        },
        {
          name:'中班',
          value: 2
        },
        {
          name:'夜班',
          value: 3
        },
        {
          name:'休息',
          value: 4
        },
        {
          name:'坐诊',
          value: 5
        },

      ]
    }
  },
  created(){
    this.createdFunc()
  },
  methods: {
    defaultShift(type,name){
      this.createdFunc(type, name)
    },
    
    ulClick(e){ 
      // console.log(e.currentTarget.firstElementChild.firstElementChild)
      // e.currentTarget.firstElementChild.firstElementChild.click() 
    },
    createdFunc(type = '1', name="早班"){
      this.calendarList = []
      let numCount = Number(moment().endOf('month').subtract(-1, 'month').format('YYYY-MM-DD').replace(/\-/g,'')) - Number(moment().startOf('month').subtract(-1, 'month').format('YYYY-MM-DD').replace(/\-/g,''))

      for(let i = 1; i<=numCount+1; i++){
        let dateValue = moment().startOf('month').subtract(-1, 'month').format('YYYY-MM') +'-'+ (i < 10 ? '0' + i : i)
        let smallObj = []
        if(new Date(dateValue).getDay() == 0 ){
          console.log(new Date(dateValue).getDay())
          smallObj = [
            { type: 'warning', content: '休息', itemId:'4', date: dateValue }, 
          ]
        }else{
          smallObj = [
            { type: 'success', content: name, itemId: type, date: dateValue }, 
          ]
        }
        let obj = {
          date: dateValue, 
          listData: smallObj
        }
        this.calendarList.push(obj)
      }
    },
    // 移除小标签
    removeTagsClick(e,value){  
      e.stopPropagation(); 
      let newData = this.calendarList.find(item => {
        return item.date == value.date
      })
      if(newData.listData.length > 1){
        let filterData = newData.listData.filter(el => {
          return el.itemId != value.itemId
        })
        // 判断如果移除班次 去掉坐诊
        if(filterData.length == 1 && filterData[0].itemId == '5'){
          // filterData.push({ type: 'success', content: '早班', itemId:'1', date: value.date })
          filterData = [{ type: 'warning', content: '休息', itemId:'4', date: value.date }]
          
        }
        console.log(filterData)
        // 重新赋值
        newData.listData = [...filterData]

      }else{
        let arrStr = [{ type: 'warning', content: '休息', itemId:'4', date: value.date }]
        newData.listData = [...arrStr]
      }
      this.calendarList = [...this.calendarList] 
    },
    onSelect(date){ 
      this.clickDate = moment(date).format('YYYY-MM-DD') 
    },
    // 新增小标签
    addClick(num){
      let obj = {
        date: this.clickDate,
        listData: []
      }
      switch (num) {
        case 1:
          obj.listData = [{ type: 'success', content: '早班', itemId:'1', date: this.clickDate }]
          break;
        case 2:
          obj.listData = [{ type: 'success', content: '中班', itemId:'2', date: this.clickDate }]
          break;
        case 3:
          obj.listData = [{ type: 'success', content: '夜班', itemId:'3', date: this.clickDate }]
          break;
        case 4:
          obj.listData = [{ type: 'warning', content: '休息', itemId:'4', date: this.clickDate }]
          break;
        case 5:
          obj.listData = [{ type: 'success', content: '坐诊', itemId:'5', date: this.clickDate }]
          break;
        default:
      }
      
      obj = Object.assign({}, obj)

      // 取出修改的数据重新赋值 判断选项是否存在
      let boolData = this.calendarList.find(item => {
        return item.date == this.clickDate
      }).listData.find(elemt => { 
        return elemt.itemId == obj.listData[0].itemId
      })

      console.log(boolData)
      // 不存在
      if(!boolData){
        let newData = this.calendarList.find(item => {
          return item.date == this.clickDate
        })
        // 如果选择休息 就清空上班的选项
        // 如果选择坐诊，必须有上班的选项
        if(obj.listData[0].itemId == '4'){
          newData.listData = [...obj.listData]
        }else if(obj.listData[0].itemId == '5'){
          let tagsBool = newData.listData = newData.listData.filter(k => {
            return k.itemId != '4'
          })
          // 如果长度小于1 就新增两条 一条早班 一条坐诊
          if(tagsBool.length < 1){
            let newTagsArr =[{ type: 'success', content: '早班', itemId:'1', date: this.clickDate }]
            newData.listData.push(...newTagsArr,...obj.listData)
          }else{
            newData.listData.push(...obj.listData)
          }
        }else{
          newData.listData = newData.listData.filter(k => {
            return k.itemId != '4' 
          })
          
          // 判断只能选择一个班次
          let onlyFiltet = newData.listData.find(onlyItem => {
            return onlyItem.itemId == '5'
          }) 
          if(onlyFiltet){
            newData.listData = [...obj.listData,{ type: 'success', content: '坐诊', itemId:'5', date: this.clickDate }]
          }else{
            newData.listData = [...obj.listData]
          }
         
        }
        
         
      } 
       

      this.$nextTick(() => {
        this.calendarList = [...this.calendarList]
      })
      console.log(this.calendarList)
    },
    
    getListData(value) {
      let listData; 
      this.calendarList.forEach(item => {
        if(item.date === moment(value).format('YYYY-MM-DD')){
          listData = item.listData 
        }
      })
      return listData || [];
    }, 
    getMonthData(value) {
      if (value.month() === 8) {
        return 1394;
      }
    },
    
    // 搜索
    filter(inputValue, path) { 
      return path.some(option => option.name.toLowerCase().indexOf(inputValue.toLowerCase()) > -1);
    },
     
   
 
    moment,
    // 禁用
    disabledDate(current) {
      return current && current < moment().startOf('day');  //当天之前的不可选，不包括当天
      
    }, 
     
    
     
    visiblehandleCancel() {
      this.visible = false
      this.searchValue = ''
      this.searchLoading = false 
      setTimeout(() => {
        this.boxShow = false 
      }, 500)
    },
    show(type = '') { 
      this.visible = true 
      this.editShow = type 
      if(type == 'edit'){ 
        this.boxShow = true

        let sendData = {
          userId: this.row_record.userId,
          createTime: this.row_record.createTime
        } 
        SchedulingModifyQueryTbShift(sendData).then(res => {
          if(res.code != 200){
            this.$message.error(result.msg)
          }else{ 
            let newData = res.rows.map(item => {
              let obj = []
              if(item.isProvide == 1){
                obj.push({
                  type: 'success',
                  content: '坐诊',
                  itemId: '5',
                  date: item.workDate, 
                })
              } 
        
              this.userDetailData.id = item.userId
              this.userDetailData.name = item.userName
              this.userDetailData.deptId = item.deptId 
              this.userDetailData.createTime = item.createTime
             

              return {
                date: item.workDate, 
                listData: [
                  {
                    type: item.shiftTypeId === -1 ? 'warning':'success',
                    content: item.shiftTypeName,
                    itemId: item.shiftTypeId == '-1' ? '4' : item.shiftTypeId,
                    date: item.workDate, 
                  },
                  ...obj
                ]
              }
            })
            console.log(newData)
            this.$nextTick(() => {
              this.calendarList = [...newData]  
              
            })
          }
        })
      }
      this.createdFunc()
    },
     
    inputClick() {
      this.noCardShow = false
    },
 
     
    // 点击确认
    submit() {
      this.submitLoading = true


      let newData = this.calendarList.map(item => {
        // 是否排班
        let shiftTypeIdValue = item.listData.find(el => {
          return el.itemId != '5'
        })
         
        // 是否坐诊
        let isProvideValue = item.listData.find(el => {
          return el.itemId == '5'
        }) 


        return {
          userId: this.userDetailData.id,
          userName: this.userDetailData.name,
          deptId: this.userDetailData.deptId,
          workDate: item.date,
          shiftTypeId: shiftTypeIdValue.itemId == '4' ? -1 : Number(shiftTypeIdValue.itemId),
          isProvide: isProvideValue ? 1 : 0,
          createTime: this.editShow == 'edit' ? this.userDetailData.createTime : undefined
        }
      })
      console.log(newData)
      let sendData = {
        shiftList: newData, 
      }
      if(this.editShow == 'edit'){
        SchedulingUpdateTbShift(sendData).then(result =>{
          this.submitLoading = false
          if(result.code != 200){
            this.$message.error(result.message)
          }else{
            this.$message.success(result.message)
            this.visiblehandleCancel()
            this.$parent.$refs.table.loadData()
          }
        })
      }else{
        SchedulingAddTbShift(sendData).then(result => {
          this.submitLoading = false
          if(result.code != 200){
            this.$message.error(result.message)
          }else{
            this.$message.success(result.message)
            this.visiblehandleCancel()
            this.$parent.$refs.table.loadData()
          }
        })
      }
      
    },

    // 点击查询
    onSearch(value) {
      console.log(value.replace(/\s*/g, ''))
      if (this.searchValue == '') {
        this.$message.warning('请先输入需要检索的姓名')
        return false
      }

      this.searchLoading = true 
      let sendData = {
        name: this.searchValue.replace(/\s*/g, ''), 
      }
      SchedulingSelectUser(sendData).then(res => {
        this.searchLoading = false 
        if(res.code !== 200){
          this.$message.error(res.message)
        }else{
          this.boxShow = true
          this.userDetailData = res.data[0]
        }
      })
      
    },
  },
}
</script>
<style lang="less" scoped>
 
 
/deep/ .no-user-input-style {
  input {
    border-color: red !important;
  }
}
.no-user-style {
  text-align: left;
  color: red;
  position: absolute;
  top: 29px;
  margin: 0 auto;
  left: 8%;
  background-color: #fff;
  width: 235px;
  z-index: 10;
  pointer-events: none;
}
/deep/ .text-area-style {
  width: 100%;
  .ant-form-item-control-wrapper {
    width: 75% !important;
  }
}
/deep/ .has-error .ant-form-explain,
.has-error .ant-form-split {
  color: #f5222d;
  position: absolute;
  top: 12px;
  left: 13px;
  background-color: #fff;
  width: 150px;
  pointer-events: none;
}

/deep/ .ant-calendar-time-picker-btn {
  display: none !important;
}
/deep/ .ant-form-inline .ant-form-item > .ant-form-item-label {
  width: 80px !important;
}
/deep/ .ant-form-inline .ant-form-item > .ant-form-item-control-wrapper {
  width: calc(100% - 80px) !important;
}
/deep/ .input-style {
  .ant-input-affix-wrapper .ant-input:not(:last-child) {
    padding-right: 46px !important;
  }
}
 
 


.events {
  list-style: none;
  margin: 0;
  padding: 0;
  padding-left: 15px;
  height: 100%;
}
.events .ant-badge-status {
  overflow: hidden;
  white-space: nowrap;
  // width: 100%;
  text-overflow: ellipsis;
  font-size: 12px;
  
}
.notes-month {
  text-align: center;
  font-size: 28px;
}
.notes-month section {
  font-size: 28px;
}
.popover-style{
   cursor: pointer;
 }
/deep/.ant-fullcalendar-disabled-cell{
   .ant-fullcalendar-value{
     display: none !important;
   }
}
/deep/ .ant-radio-button-wrapper:last-child{
  display: none;
}
/deep/ .calendar-li-style{
  position: relative;
  
}
/deep/ .calendar-li-icon-style{
  font-size: 13px;
  position: absolute;
  right: 15px;
  top: 3px;
  cursor: pointer; 
  width: 50px;
  display: block;
}
// /deep/  .ant-fullcalendar-selected-day .ant-fullcalendar-value{
//   color: #fff !important;
// }
/deep/ .add-btn-style-pos-box{
  position: relative;
  margin-top: 20px;
}
/deep/ .add-btn-style-pos{
  position: absolute;
  width: 100%;
  top: 10px;
  left: 20px;
}
</style>